package com.hc.android.research.views;

import com.hc.android.research.AndroidResearchActivity;
import com.hc.android.research.R;
import com.hc.android.research.persistence.ResearchDAO;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SettingsView extends Activity implements OnClickListener
{
	public static String SETTING_DELAY_NAME = "updateDelay";
	private static int SAVE_SETTING_ERROR_DIALOG = 1;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settingsview);
		
		Button saveBtn = (Button)findViewById(R.id.saveBtn);
		saveBtn.setOnClickListener(this);
		
		ResearchDAO researchDAO = new ResearchDAO();
		String settingValue = researchDAO.getSetting(this, SETTING_DELAY_NAME);
		Integer timeInt = 30;
		try
		{
			timeInt = Integer.parseInt(settingValue);
			timeInt = (timeInt / 1000);
		}
		catch(Exception e)
		{}
		
		TextView textView = (TextView)findViewById(R.id.timeTxt);
		textView.setText(""+timeInt);
	}

	@Override
	protected void onPause() 
	{
		super.onPause();
		// Another activity is taking focus (this activity is about to be
		// "paused").
	}

	public void onClick(View v) 
	{
		try
		{
			//validate text
			String inputValue = ((TextView) findViewById(R.id.timeTxt)).getText().toString();
			Integer timeInt = Integer.parseInt(inputValue);
			Integer timeMillis = (timeInt * 1000);//get milliseconds
			//if valid return to main
			ResearchDAO researchDAO = new ResearchDAO();
			researchDAO.updateSetting(this, SETTING_DELAY_NAME, timeMillis.toString());
			
			AndroidResearchActivity.updatePendingBackgroundService(this);
			
			Intent intent = new Intent(this, AndroidResearchActivity.class);
			startActivity(intent);
		}
		catch(Exception e)
		{
			//else clear and display error
			onCreateDialog(SAVE_SETTING_ERROR_DIALOG).show();
		}
		
	}
	
	@Override
	protected Dialog onCreateDialog(int id) 
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Unable to save settings. Try Again.");
		builder.setCancelable(false);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {			
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();				
			}
		});
		
		return builder.create();
	}
}
